package com.sso.service;

import com.aaa.entity.TabMenu;
import com.aaa.entity.TabRole;
import com.aaa.entity.TabUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sso.feign.UserFeign;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MyUserService implements UserDetailsService {

    @Resource
    private UserFeign userFeign;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // s 代表的是输入的用户的名字

        //System.out.println(userFeign);
        // 根据用户的名字  获取用户的信息
        TabUser tabUser = userFeign.getTabUserByName(s);
        if (tabUser==null){
            System.out.println("当前的用户不存在");
            throw new BadCredentialsException("用户名或者密码错误");
        }else{
            // 用户存在的   密码 密文
            // 对应的资源的信息  1. 角色的信息   2. 资源的信息
            // 根据用户的id  需要查询该用户对应的所有的角色的编码
            Integer id = tabUser.getId();
            System.out.println("-----------"+id);
            List<TabRole> roleList = userFeign.getRoleByUid(id);
            System.out.println("角色的信息:"+roleList);
            // 角色的code 存放到对应的资源里面
            List<SimpleGrantedAuthority> roles = roleList.stream().map(tabRole -> new SimpleGrantedAuthority("ROLE_"+tabRole.getRcode())).collect(Collectors.toList());
            //根据当前用户的角色的id 资源
            List<Integer> rids = roleList.stream().map(tabRole -> tabRole.getRid()).collect(Collectors.toList());
            // 根据角色的id 查询对应的菜单的信息
            // 发送json数据

            List<TabMenu> menuList =  userFeign.getMenusByRids(rids);
            System.out.println("当前角色的所有的菜单的信息:"+menuList);
            // 角色的信息   还有资源的信息
            List<SimpleGrantedAuthority> menus = menuList.stream().map(tabMenu -> new SimpleGrantedAuthority(tabMenu.getMname())).collect(Collectors.toList());
            // stream 合并   concat
            List<SimpleGrantedAuthority> authorities = Stream.concat(roles.stream(), menus.stream()).collect(Collectors.toList());
            User user = new User(s,tabUser.getPassword(),authorities);
            return user;
        }
//        return null;
    }
}
